package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.CheckItemDao;
import com.itheima.dao.CheckgroupDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collections;
import java.util.List;

@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;

    @Autowired
    private CheckgroupDao checkgroupDao;

    @Autowired
    private CheckItemDao checkItemDao;
    @Override
    public PageInfo<Setmeal> findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());

        List<Setmeal> setmealList =  setmealDao.findPage(queryPageBean.getQueryString());

        PageInfo<Setmeal> pageInfo = new PageInfo<>(setmealList);
        return pageInfo;
    }

    @Override
    public void add(Setmeal setmeal, int[] checkgroupIds) {
        //添加数据到套餐表 、
        setmealDao.add2Setmeal(setmeal);
        // 获取新增套餐的主键 、
        Integer setmealId = setmeal.getId();
        if (checkgroupIds != null) {
            for(int checkgroupId:checkgroupIds){
                // 添加数据到中间表
                setmealDao.add2Mid(setmealId,checkgroupId);
            }
        }
    }

    @Override
    public List<Setmeal> getAllSetmeal() {
        List<Setmeal> setmeals = setmealDao.getAllSetmeal();
        return setmeals;
    }

    @Override
    public Setmeal findById(int id) {
        //很多代码
        Setmeal setmeal = setmealDao.findById(id);
        //1.根据套餐id查询套餐对应的检查组数据
        List<CheckGroup> checkGroups =  checkgroupDao.findCheckGroupsBySetmealId(id);
        //3.遍历checkGroups
        for(CheckGroup checkGroup:checkGroups){
            //4.拿到检查组id
            Integer checkGroupId = checkGroup.getId();
            //5.根据检查组id查询对应的检查项数据
            List<CheckItem> checkItems =  checkItemDao.findCheckItemsByCheckGroupId(checkGroupId);
            //6.把查询到的检查项数据赋值给CheckGroup对象
            checkGroup.setCheckItems(checkItems);
        }

        //2.把查询到的检查组数据赋值给setmeal对象
        setmeal.setCheckGroups(checkGroups);
        return setmeal;
    }
}
